import store from "./store";
import router from "./router";
import NProgress from 'nprogress'
import vue from 'vue'
import {get,remove} from "@/utils/Auth";
import constans from '@/constants/constants.json'
import 'nprogress/nprogress.css'// progress bar style
let instance=new vue();
router.beforeEach((to,from,next)=>{
    NProgress.start();
    //全局长连接
    let socket=store.getters.GET_SOCKET;
    let url=process.env.NODE_ENV === 'development'?constans.websocket:`ws://${window.location.host}/system-socket`;
    if (socket.readyState!=1){
        socket=new WebSocket(url);
        socket.onopen=()=>{
            console.log('已连接')
        }
        socket.onclose = function (e) {
            console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)

        }
        store.commit('SET_SOCKET',socket);
    }
    if (to.path==='/login'){
        store.dispatch('GET_AUTH').then(res=>{
            store.commit('SET_STATUS',false);
            remove();
            next();
        })
    }else{
        store.dispatch('GET_AUTH').then(result=>{
            if (instance.isEmptyObject(result)){
                store.commit('SET_STATUS',true);
                filter(next,NProgress);
            }else{
                let user=get();
                if (instance.isNullOrEmpty(user)){
                    store.commit('SET_STATUS',false);
                    next({
                        path:'/login',
                        replace: true
                    })
                }else{
                    store.commit('SET_STATUS',true);
                    filter(next,NProgress)
                }


            }
        })
    }




})

router.afterEach(() => {
    NProgress.done() // finish progress bar
})

function filter(next,NProgress){
    if (!instance.isEmptyObject(store.getters.getSysInfo) && !instance.isEmptyObject(store.getters.getHeartRule)){
        next();
    }else{
        store.dispatch('getBaseInfo').then(res=>{
            if (!instance.isEmptyObject(store.getters.getHeartRule)){
                next();
            }else{
                store.dispatch('getRules').then(response=>{
                    next()
                }).catch(()=>{
                    NProgress.done();
                })
            }

        }).catch(()=>{
            NProgress.done();
        })
    }
}